﻿using EntityModels.Entities;
using EntityModels.Normal;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System.Text.Json;

namespace EntityModels.DbContexts
{
    /// <summary>
    /// 值比较器和属性快照
    /// </summary>
    public class ValueComparerDbContext : DbContext
    {
        public DbSet<ValueComparerEntity> ValueComparerEntities => Set<ValueComparerEntity>();

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ValueComparerEntity>()
                .Property(e => e.SimpleClass)
                .HasConversion(
                    v => v.Value,
                    v => new ImmutableClass(v));

            modelBuilder.Entity<ValueComparerEntity>()
                .Property(e => e.SimpleStruct)
                .HasConversion(
                    v => v.Value,
                    v => new ImmutableStruct(v)
                );

            var valueComparer = new ValueComparer<List<int>>(
                    // 相等性判断表达式
                    (c1, c2) => c1.SequenceEqual(c2),
                // HashCode生成表达式
                c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())),
                // 跟踪快照生成表达式
                c => c.ToList()
                );

            modelBuilder.Entity<ValueComparerEntity>()
            .Property(e => e.OrdinaryClass)
            .HasConversion(
                v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null),
                v => JsonSerializer.Deserialize<List<int>>(v, (JsonSerializerOptions)null),
                // 引用值比较器
                valueComparer);
        }
    }
}
